package logic

import (
	"autotestservice/testservices/internal/data"
	"autotestservice/testservices/internal/deviceMng"
	"context"
	"encoding/json"
	"gitee.com/jmdvirus/jkgo/jk/jklog"
	"github.com/tal-tech/go-zero/core/hash"
	"math/rand"
	"strconv"
	"time"

	"autotestservice/testservices/internal/svc"
	"autotestservice/testservices/internal/types"

	"github.com/tal-tech/go-zero/core/logx"
)

type AutotestItemTestLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAutotestItemTestLogic(ctx context.Context, svcCtx *svc.ServiceContext) AutotestItemTestLogic {
	return AutotestItemTestLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AutotestItemTestLogic) AutotestItemTest(req types.TestProjectItem) (*types.Response, error) {
	jklog.L().Debugln("test item ", req.Name)

	res := types.Response{
		Code:    200,
		Message: "success",
	}
	devOpt := deviceMng.NewDeviceOption(req.TestTarget.ConnectStyle, req.TestTarget.Addr, req.TestTarget.Port)
	findDev := deviceMng.GlobalDeviceMng().Find(*devOpt)

	if findDev != nil {
		now := time.Now().Unix()
		tran := hash.Md5Hex([]byte(strconv.FormatInt(now, 10) + req.Content))
		cmd := deviceMng.DeviceOptionTestCmd{
			Timestamp:   time.Now().Unix(),
			Cmd:         req.Content,
			PreResult:   req.PreResult,
			Transaction: tran,
		}
		req.TimeStart = now
		r, _ := findDev.Test(cmd)
		req.TimeEnd = time.Now().Unix()
		devRes := types.Response{}
		jklog.L().Infoln("device response ", r)
		json.Unmarshal([]byte(r), &devRes)

		rand.Seed(time.Now().UnixNano())
		iid := rand.Int63n(1000000) + 100000
		dbreq := data.DBTestProjectItem{
			Id:         strconv.FormatInt(time.Now().Unix(), 10) + strconv.FormatInt(iid, 10),
			TestId:     req.TestId,
			ProjectId:  req.ProjectId,
			Name:       req.Name,
			Result:     devRes.Code == 0,
			Content:    req.Content,
			RealResult: devRes.Message,
			PreResult:  req.PreResult,
			TimeStart:  req.TimeStart,
			TimeEnd:    req.TimeEnd,
		}
		_, err := data.AutoTestTestProjectItemSet(dbreq)
		if err != nil {
			jklog.L().Errorln(err)
			res.Code = 505
			res.Message = "set fail"
			return &res, nil
		}
	} else {
		res.Code = 1
		res.Message = "not connect"
	}

	return &res, nil
}
